import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      // 未授权，跳转到登录页
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// API接口定义
export interface AIResponse {
  id: string
  content: string
  model: string
  timestamp: string
}

export interface UserInfo {
  id: string
  username: string
  vipStatus: string
  battery: number
}

export interface AIModel {
  id: string
  name: string
  icon: string
  selected: boolean
  free: boolean
}

// API方法
export const apiService = {
  // 用户相关
  getUserInfo: () => api.get<UserInfo>('/user/info'),
  updateUserInfo: (data: Partial<UserInfo>) => api.put('/user/info', data),

  // AI模型相关
  getAIModels: () => api.get<AIModel[]>('/ai/models'),
  selectAIModel: (modelId: string) => api.post(`/ai/models/${modelId}/select`),

  // 对话相关
  sendMessage: (message: string, modelIds: string[]) => 
    api.post<AIResponse>('/chat/send', { message, modelIds }),
  
  getChatHistory: (page: number = 1, size: number = 20) => 
    api.get('/chat/history', { params: { page, size } }),

  // 文件上传
  uploadFile: (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/upload/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },
}

export default api 